using Godot;
using System;

namespace TopDownGodot.Src.Multiplayer
{
    public partial class ConnectServer : Node
    {
        private readonly PackedScene _characterChoicesScene = GD.Load<PackedScene>("res://scene/character_choices.tscn");
        private readonly PackedScene _MultiplayerScene = GD.Load<PackedScene>("res://scene/multiplayer_scene.tscn");

        // 绑定节点路径
        private LineEdit IpField => GetNode<LineEdit>("GUI/Text/Ip");
        private LineEdit PortField => GetNode<LineEdit>("GUI/Text/Port");
        private LineEdit PasswordField => GetNode<LineEdit>("GUI/Text/Password");

        public override void _Ready()
        {
            Multiplayer.ConnectionFailed += ConnectionFailedInfo;
            Multiplayer.ConnectedToServer += ConnectedToServerChangeScene;
        }

        public void OnConnectButtonPressed()
        {
            string ip = IpField.Text;
            int port = int.TryParse(PortField.Text, out var p) ? p : 0;
            _ = PasswordField.Text;
            GD.Print(ip);
            GD.Print(port);


            var peer = new ENetMultiplayerPeer();
            peer.CreateClient(ip, port);
            Multiplayer.MultiplayerPeer = peer;
            GD.Print("连接中……");
        }

        private void ConnectionFailedInfo()
        {
            GD.Print("连接失败");
        }

        private void ConnectedToServerChangeScene()
        {
            GD.Print("连接成功");
            GetTree().ChangeSceneToPacked(_characterChoicesScene);
        }

        public void OnBackButtonButtonPressed()
        {
            GetTree().ChangeSceneToPacked(_MultiplayerScene);
        }
    }
}